package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.mapper.UserMapper;
import com.tanhua.model.db.User;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@DubboService
public class UserApiImpl implements UserApi {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过手机号码查询
     *
     * @param phone
     * @return
     */
    @Override
    public User findByMobile(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        // selectOne 只查询一条记录，如果有多条，则报错 too many result
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 注册新用户
     *
     * @param loginUser
     * @return
     */
    @Override
    public Long add(User loginUser) {
        Date date = new Date();
        // 由自动填充代替
        //loginUser.setUpdated(date);
        //loginUser.setCreated(date);
        // mybatis的dao接口方法返回值，如果增删改，返回的是受影响的行数
        userMapper.insert(loginUser);
        return loginUser.getId();
    }

    /**
     * 更新用户 的环信账号
     *
     * @param huanXinUser
     */
    @Override
    public void update(User huanXinUser) {
        userMapper.updateById(huanXinUser);
    }

    /**
     * 通过环信账号查询用户
     *
     * @param huanxinId
     * @return
     */
    @Override
    public User findByHuanXinUser(String huanxinId) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getHxUser, huanxinId);
        return userMapper.selectOne(lqw);
    }
}
